package com.dirk.happie.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.adapters.ArticleSizeListAdapter;
import com.dirk.happie.beans.ArticleBean;
import com.dirk.happie.beans.ExtraBean;
import com.dirk.happie.beans.OptionsBean;
import com.dirk.happie.network.GetArticlesTask;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.utils.ImageDownloader;
import com.dirk.happie.utils.Keys;
import com.dirk.happie.utils.LogoDownloader;

public class ArticleSizeActivity extends Activity {

	private GetArticlesTask getArticlesTask = null;
	private App mApp;

	ArrayList<ArticleBean> product_data;

	List<ArticleBean> articles;

	Bitmap bitmap;

	private String categoryId;
	private String articleId;
	// private String companyId;
	private List<String> extraIds = new ArrayList<String>();

	private String articleImage;
	private String articleName;
	private String articleDescription;

	RelativeLayout extraLayout;
	LinearLayout extraLinearTop;
	LinearLayout extraLinearBottom;

	private ImageDownloader imageDownloader = null;
	private String cacheFolderPath = "";

	private LogoDownloader logoDownloader = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_article_size);
		this.mApp = ((App) getApplication());

		ImageView companyLogoView = (ImageView) findViewById(R.id.img_company);
		cacheFolderPath = Environment.getExternalStorageDirectory().getPath() + "/happie_cache";
		File file = new File(cacheFolderPath);
		file.mkdirs();
		logoDownloader = new LogoDownloader();
		if (mApp.getCompanyLogo() != null) {
			logoDownloader.download(Keys.LOGOS_URL + mApp.getCompanyLogo(), cacheFolderPath + "/" + Common.getMD5(mApp.getCompanyLogo()), companyLogoView);
		}
		product_data = new ArrayList<ArticleBean>();

		categoryId = getIntent().getStringExtra(Keys.KEY_CATEGORY_ID);
		articleId = getIntent().getStringExtra(Keys.KEY_ARTICLE_ID);
		// companyId = getIntent().getStringExtra(Keys.KEY_COMPANY_ID);

		imageDownloader = new ImageDownloader();

		extraLayout = (RelativeLayout) findViewById(R.id.extraOption);
		extraLinearTop = (LinearLayout) findViewById(R.id.extraLinearTop);
		extraLinearBottom = (LinearLayout) findViewById(R.id.extraLinearBottom);

		parseArticlesJSON();

		footerMenuListeners();

	}

	private void initProductDescLayout() {
		TextView productTitle = (TextView) findViewById(R.id.txtTitle);
		productTitle.setText(articleName);

		TextView productSpecs = (TextView) findViewById(R.id.txtSpecs);
		productSpecs.setText(articleDescription);

		ImageView productImage = (ImageView) findViewById(R.id.imgProduct);

		if (articleImage != null) {

			imageDownloader.download(Keys.IMAGES_URL + articleImage, cacheFolderPath + "/" + Common.getMD5(articleImage), productImage);
		}

	}

	private void initListView() {

		LinearLayout lv = (LinearLayout) findViewById(R.id.listProducts);
		ArticleSizeListAdapter adapter = new ArticleSizeListAdapter(this, R.layout.article_size_list_item, product_data);
		int count = adapter.getCount();
		for (int i = 0; i < count; i++) {
			final int position = i;
			View view = adapter.getView(i, null, null);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ArticleSizeActivity.this, BasketActivity.class);
					intent.putExtra(Keys.KEY_ARTICLE_ID, product_data.get(position).getArticleId());
					intent.putExtra(Keys.KEY_CATEGORY_ID, product_data.get(position).getCategoryId());
					if (product_data.get(position).getOptionId() != null) {
						intent.putExtra(Keys.KEY_OPTION_ID, product_data.get(position).getOptionId());
					}
					String[] extraIDs = new String[extraIds.size()];
					for (int i = 0; i < extraIds.size(); i++) {
						extraIDs[i] = extraIds.get(i);
					}
					intent.putExtra(Keys.KEY_EXTRA_CHECK, extraIDs);
					// intent.putExtra(Keys.KEY_COMPANY_ID, companyId);
					startActivityForResult(intent, 10);
				}
			});
			lv.addView(view);

		}

	}

	private void parseArticlesJSON() {

		getArticlesTask = new GetArticlesTask(this);
		getArticlesTask.setRequestCompleteListener(new RequestCompleteListener<List<ArticleBean>>() {

			@Override
			public void onSuccess(List<ArticleBean> result) {
				articles = result;
				if (articles != null) {
					for (int i = 0; i < articles.size(); i++) {
						ArticleBean curArticle = articles.get(i);
						if (curArticle.getArticleId().equals(articleId)) {
							if (Common.compareOfferDate(curArticle)) {
								curArticle.setArticlePrice(curArticle.getOfferPrice());
							}

							product_data.add(curArticle);
							articleName = curArticle.getArticleName();
							articleDescription = curArticle.getArticleDescription();
							articleImage = curArticle.getArticlePicture();
							if (curArticle.getOption() != null && curArticle.getOption().size() > 0) {
								for (OptionsBean option : curArticle.getOption()) {
									ArticleBean bean = new ArticleBean(curArticle);
									bean.setArticleDescription(option.getOptionDescription());
									bean.setArticleSize(option.getOptionSize());
									bean.setArticlePrice(option.getOptionPrice());
									bean.setOptionId(option.getIdOption());
									product_data.add(bean);
								}
							}

							if (curArticle.getExtra() != null && curArticle.getExtra().size() > 0) {
								extraLayout.setVisibility(View.VISIBLE);

								for (final ExtraBean extra : curArticle.getExtra()) {

									RelativeLayout checkLayout = new RelativeLayout(ArticleSizeActivity.this);

									final CheckBox extraCheck = new CheckBox(ArticleSizeActivity.this);
									extraCheck.setText(extra.getExtraDescription());

									RelativeLayout.LayoutParams paramsCheckPrice = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
									paramsCheckPrice.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

									TextView priceText = new TextView(ArticleSizeActivity.this);
									priceText.setText(getString(R.string.currency) + " " + Common.getPrice(extra.getExtraPrice()));
									priceText.setLayoutParams(paramsCheckPrice);

									checkLayout.addView(extraCheck);
									checkLayout.addView(priceText);

									extraLinearBottom.addView(checkLayout);
									RelativeLayout extraRelativeTop = new RelativeLayout(ArticleSizeActivity.this);
									final TextView extraText = new TextView(ArticleSizeActivity.this);
									extraText.setText(extra.getExtraDescription());

									final TextView extraPriceTextView = new TextView(ArticleSizeActivity.this);
									extraPriceTextView.setText(getString(R.string.currency) + " " + extra.getExtraPrice());
									RelativeLayout.LayoutParams paramsPrice = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
									paramsPrice.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
									extraPriceTextView.setLayoutParams(paramsPrice);

									if (extraCheck.isChecked()) {
										extraText.setVisibility(View.VISIBLE);
										extraPriceTextView.setVisibility(View.VISIBLE);
									} else {
										extraText.setVisibility(View.GONE);
										extraPriceTextView.setVisibility(View.GONE);
									}

									extraRelativeTop.addView(extraText);
									extraRelativeTop.addView(extraPriceTextView);

									extraLinearTop.addView(extraRelativeTop);

									extraCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {

										@Override
										public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
											extraCheck.setChecked(isChecked);
											if (isChecked) {
												extraText.setVisibility(View.VISIBLE);
												extraPriceTextView.setVisibility(View.VISIBLE);
												extraIds.add(extra.getIdExtra());
											} else {
												extraText.setVisibility(View.GONE);
												extraPriceTextView.setVisibility(View.GONE);
												extraIds.remove(extra.getIdExtra());
											}
										}
									});
								}
							}

						}
					}
					initProductDescLayout();
					initListView();
				}
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			getArticlesTask.execute(categoryId);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}

	}

	private void footerMenuListeners() {

		View homeButton = findViewById(R.id.home);
		homeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(100);
				finish();
			}
		});

		View categoriesButton = findViewById(R.id.categories);
		categoriesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(200);
				finish();
			}
		});

		View basketButton = findViewById(R.id.basket);
		basketButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ArticleSizeActivity.this, BasketActivity.class);
				intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
				startActivityForResult(intent, 10);
			}
		});

		View searchButton = findViewById(R.id.search);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		switch (resultCode) {
		case 100:
			finish();
			break;

		case 200:
			finish();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		if (logoDownloader != null) {
			logoDownloader.clearImages();
		}
		if (getArticlesTask != null) {
			getArticlesTask.setRequestCompleteListener(null);
		}
		super.onDestroy();
	}

}
